<?php
/**
 * Created by PhpStorm.
 * User: wzy12
 * Date: 2018/10/14
 * Time: 14:44
 */

namespace app\common\model;


use think\Model;

class Ad extends Model
{
    public function operation($data){
        $query = $this -> where('ad_name', $data['ad_name']) -> where('position_id', $data['position_id']);
        $action = false;
        if(isset($data['id'])){
            $action = true;

            $query -> where('id', '<>', $data['id']);
        }else{
            $data['link_add'] = session('user.username');
            $data['link_email'] = session('user.email');
            $data['link_phone'] = session('user.phone');
        }
        // 判断该广告位置下是否有该广告
        $res = $query -> value('id');
        if($res){
            return echoArr(0, '该广告位置下已有此广告');
        }

        $result = $this -> validate('Ad.form') -> allowField(true) -> isUpdate($action) -> save($data);
        if(false === $result){
            return echoArr(0, $this -> getError());
        }else{
            return echoArr(1, '操作成功');
        }
    }

    public function del($data){
        $result = $this -> destroy($data);

        if(false === $result){
            return echoArr(0, '操作失败');
        }else{
            return echoArr(1, '操作成功');
        }
    }

    public function resList($where){
        $query = $this -> where(1);

        // 筛选条件
        $is_where = $where;
        unset($is_where['page']);
        if($is_where) {
            if ($where) {
                // 查询广告位置的广告
                if ($where['position_id']) {
                    $query->where('position_id', $where['position_id']);
                }

                // 查询广告名称
                if ($where['ad_name']) {
                    $query->where('ad_name', 'like', "%{$where['ad_name']}%");
                }
            }
        }

        $arr['list'] = $this -> alias('a') -> join('AdPosition p', 'a.position_id = p.id') -> field('a.*,p.position_name') -> order('sort desc,id') -> paginate(10, false, ['query'=>request()->param()]);

        // 广告位置列表
        $arr['ad_position'] = model('AdPosition') -> select();

        return $arr;
    }

    /**
     * 更改排序
     */
    public function editSort($data){
        $result = $this -> validate('Ad.sort') -> allowField(true) -> isUpdate(true) -> save($data);

        if(false === $result){
            return echoArr(0, $this -> getError());
        }else{
            return echoArr(1, '更新成功');
        }
    }

    /**
     * 更改状态
     */
    public function editStatus($data){
        $result = $this -> validate('Ad.status') -> allowField(true) -> isUpdate(true) -> save($data);

        if(false === $result){
            return echoArr(0, $this -> getError());
        }else{
            return echoArr(1, '操作成功');
        }
    }
}